package com.cby.user.controller;


import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.cby.exception.CbyException;
import com.cby.other.R;
import com.cby.user.entity.CbyUser;
import com.cby.user.entity.query.CbyUserQuery;
import com.cby.user.entity.vo.CbyUserTableVo;
import com.cby.user.entity.vo.CbyUserVo;
import com.cby.user.service.CbyIdentityService;
import com.cby.user.service.CbyUserService;
import com.cby.user.util.JwtUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.*;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author wskh
 * @since 2021-11-03
 */
@Api(tags = "用户管理")
@RestController
@RequestMapping("/user/cby_user")
@CrossOrigin
public class CbyUserController {

    @Autowired
    CbyUserService userService;
    @Autowired
    CbyIdentityService identityService;
    @Autowired
    RedisTemplate<String,String> redisTemplate;

    @ApiOperation(value = "查询全部用户")
    @GetMapping("getAllUser")
    public R getAllUser(){
        return R.ok().data("items",userService.list());
    }



    @ApiOperation(value = "条件分页查询用户")
    @PostMapping("queryUser/{current}/{limit}")
    public R queryUser(@PathVariable long current, @PathVariable long limit,
                       // RequestBody：自动将前端传过来的json转换为对应的对象
                       // required = false，对象中的某些属性可以为空
                       @RequestBody(required = false) CbyUserQuery cbyUserQuery){
        return userService.queryUser(current,limit,cbyUserQuery);
    }

    @ApiOperation(value = "登录验证请求")
    @PostMapping("login/{name}/{password}")
    public R login(@PathVariable String name, @PathVariable String password, HttpServletRequest request){
        return userService.login(name,password);
    }

    @ApiOperation(value= "退出登录 清除redis中的token")
    @GetMapping("/logout")
    // @RequestHeader("Authorization") String token
    public R logout(HttpServletRequest request){
//        Enumeration<String> headerNames = request.getHeaderNames();
//        String next = null;
//        while ((next=headerNames.nextElement())!=null){
//            System.out.println(next);
//        }
        String token = request.getHeader("Authorization");
        // 判断token是否存在
        String s = redisTemplate.opsForValue().get("userToken" + token);
        if(StringUtils.isEmpty(s)){
            return R.ok("退出登录成功");
        }
        redisTemplate.delete("userToken"+token);
        return R.ok("退出登录成功");
    }

    @ApiOperation(value = "获取当前用户")
    @GetMapping("/getCurrentUser")
    public R getCurrentUser(@RequestHeader("Authorization") String token){
        // 判断token是否为空
        if(org.apache.commons.lang3.StringUtils.isBlank(token)){
            return R.error("token为空");
        }
        // 判断token是否解析成功
        Map<String, Object> stringObjectMap = JwtUtil.checkToken(token);
        if(stringObjectMap==null){
            return R.error("token解析失败");
        }
        // 判断redis中是否存在token
        String userJson = redisTemplate.opsForValue().get("userToken" + token);
        if(org.apache.commons.lang3.StringUtils.isBlank(userJson)){
            return R.error("redis中找不到该token");
        }
        // 返回userJson
        return R.ok(userJson);
    }

    @ApiOperation(value = "根据token获取用户登录信息")
    @GetMapping("info")
    public R getLoginInfo(HttpServletRequest request,@RequestParam String token){
        try {
            String memberId = JwtUtil.getMemberIdByJwtToken(token);
            CbyUser user = userService.getById(memberId);
            if(user==null){
                throw new CbyException(500,"获取登录信息失败");
            }
            return R.ok().data("roles",identityService.getById(user.getIdentityId()).getName()).data("name",user.getNickName()).data("avatar","https://wpimg.wallstcn.com/f778738c-e4f8-4870-b634-56703b4acafe.gif");
        }catch (Exception e){
            e.printStackTrace();
            throw new CbyException(500,"获取登录信息失败");
        }
    }

    @ApiOperation(value = "发送验证码")
    @PostMapping("/sendVerificationCode/{email}")
    public R sendVerificationCode(@PathVariable String email){
        return userService.sendVerificationCode(email);
    }

    @ApiOperation(value = "注册")
    @PostMapping("/register")
    public R register(@RequestBody CbyUserVo cbyUserVo){
        return userService.register(cbyUserVo);
    }

    @ApiOperation(value = "找回密码")
    @PostMapping("/retrievePassword/{phone}/{email}")
    public R retrievePassword(@PathVariable String phone,@PathVariable String email){
        return userService.retrievePassword(phone,email);
    }

    @ApiOperation(value = "测试3d场景")
    @GetMapping("/test3D")
    public R test3D(){
        return userService.test3D();
    }

    @ApiOperation("获取绘制面积图的注册量数据")
    @GetMapping("/getPlotData")
    public R getPlotData(){
        return userService.getPlotData();
    }

}

